<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
    @cancel="closeFn"
  >
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
<!--    w-1/4 xl:w-1/5-->
    <DeptTree class="w-2/5 xl:w-2/5" @select="handleSelect" />
<!--    w-3/4 xl:w-4/5-->
    <BasicTable @register="registerTable" class="w-3/5 xl:w-3/5" :searchInfo="searchInfo">
      <template #toolbar>
<!--        <a-button type="primary" @click="handleCreate">新增账号</a-button>-->
        <a-button type="primary" @click="handleExport" :loading="syncLoadLoading">同步钉钉人员信息</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'clarity:info-standard-line',
                tooltip: '查看用户详情',
                onClick: handleView.bind(null, record),
              },
              {
                icon: 'clarity:note-edit-line',
                tooltip: '编辑用户资料',
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                tooltip: '删除此账号',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <AccountModal @register="registerModal" @success="handleSuccess"/>
  </PageWrapper>
  </BasicModal>

</template>
<script lang="ts" setup>
import {reactive, unref,ref} from 'vue';

  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { deptUserListApi,syncDeptListApi } from '@/api/sys/sysData';
  import { PageWrapper } from '@/components/Page';
  import { BasicModal, useModalInner } from '@/components/Modal';

  import DeptTree from './DeptTree.vue';

  import { useModal } from '@/components/Modal';
  import AccountModal from './AccountModal.vue';

  import { columns, searchFormSchema } from './account.data';
  import { useGo } from '@/hooks/web/usePage';
  import {useMessage} from "@/hooks/web/useMessage";
  import { useUserStore } from '@/store/modules/user';
  const userStore = useUserStore();

 const emit = defineEmits(['success']);

  const { createMessage } = useMessage();

  defineOptions({ name: 'AccountManagement' });
  const props = defineProps({
    mode: { type: String,default:"multiple" },
   }  );

  let str=""

  const selectIds = ref([]);
  const syncLoadLoading=ref(false);
  const go = useGo();
  const [registerModal, { openModal }] = useModal();
  const searchInfo = reactive<Recordable>({});
  const [registerTable, { reload, updateTableDataRecord, getSearchInfo,clearSelectedRowKeys,getSelectRows,setSelectedRowKeys }] = useTable({
    title: '账号列表',
    api: deptUserListApi,
    rowKey: 'userId',
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
    },

    rowSelection:{
      onChange: (selectedRowKeys: (string | number)[], selectedRows: DataItem[]) => {
      //  console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        selectIds.value=selectedRows
      },
      onSelect: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
      //  console.log(record, selected, selectedRows);
      },
      onSelectAll: (selected: boolean, selectedRows: DataItem[], changeRows: DataItem[]) => {
        // console.log("--onSelectAll")
        // console.log(selected, selectedRows, changeRows);
      },

    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    handleSearchInfoFn(info) {
      console.log('handleSearchInfoFn', info);
      return info;
    },
    // actionColumn: {
    //   width: 120,
    //   title: '操作',
    //   dataIndex: 'action',
    // },
  });



  const [register, { setModalProps, closeModal }] = useModalInner( async(data) => {
    clearSelectedRowKeys();

    //打开弹层
   // console.log("---接收data",data.ids)
    if(data.ids){
     let arr= data.ids.split(",");
      setSelectedRowKeys(arr);
    }
   // console.log("----clearSelectedRowKeys::")
    // debugger
  });


  const getTitle="选择人员";
  const isUpdate=ref(false);
  function handleCreate() {
    openModal(true, {
      isUpdate: false,
    });
    isUpdate.value=false;

   // userStore.setChatIsUpdate(false);
  }

  function handleEdit(record: Recordable) {
    console.log(record);
    openModal(true, {
      record,
      isUpdate: true,
    });
    isUpdate.value=true;
   // userStore.setChatIsUpdate(true);

  }

  async function handleSubmit() {
    let selectRows = getSelectRows();


    if(!selectRows.length){
      createMessage.error("请先勾选人员!");
      return false;
    }
  //  console.log("---props.mode",props.mode)
    if(props.mode==="single"){
      if(selectRows.length>1){
        createMessage.error("请只选择一条数据!");
        return false;
      }
    }
    // console.log("---selectRows",selectRows);
    emit('success',selectRows);
    closeFn();
   // console.log("----selectIds",selectIds.value)
  }

  function handleDelete(record: Recordable) {
    console.log(record);
  }

  function handleExport() {
    // console.log(getSearchInfo());
    syncLoadLoading.value=true;
    syncDeptListApi().then(res=>{
      syncLoadLoading.value=false;

      if(code==200){
        createMessage.success(res.message);
        reload();
      }else{
        createMessage.error(res.message);
      }

    })
  }

  function handleSuccess({ isUpdate, values }) {
    if (isUpdate) {
      // 演示不刷新表格直接更新内部数据。
      // 注意：updateTableDataRecord要求表格的rowKey属性为string并且存在于每一行的record的keys中
      const result = updateTableDataRecord(values.id, values);
    //  console.log(result);
    } else {
      reload();
    }
  }

  function handleSelect(deptId = '') {
    searchInfo.deptId = deptId;
    reload();
  }

  function closeFn(){
    clearSelectedRowKeys();
    closeModal()
  }



  function handleView(record: Recordable) {
    go('/system/account_detail/' + record.chatid);
  }
</script>
